//
//  PictureBrowserViewController.swift
//  MicroBlog
//
//  Created by 002 on 15/10/28.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit
import SVProgressHUD

private let PhotoBrowserCellId = "PhotoBrowserCellId"

class PhotoBrowserViewController: UIViewController {

    /// 当前所选图片的索引
    private var currentIndexPath : NSIndexPath
    /// 照片 URL 数组
    private var urls : [NSURL]
    
    // MARK: - 监听方法
    // 保存图片
    @objc private func save() {
//        print("保存图片save")
        
        // 1. 获取所选的cell
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        
        // 2. 获取cell的图片
        guard let image = cell.imageView.image else {
            print("保存图片出错")
            return
        }
        
        // 3. 保存到相册
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    @objc private func image(image: UIImage,didFinishSavingWithError error: NSError?,contextInfo: AnyObject?) {
        
        let message = error == nil ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)        
    }
    
    // MARK: 关闭视图浏览器
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 构造函数 urls 和 currentIndexPath 都是必选的，所以不必考虑后续解包的问题
    init(indexPath : NSIndexPath, urls : [NSURL]) {
        
        // 初始化成员变量
        self.currentIndexPath = indexPath
        self.urls = urls
        
        // 调用父类默认构造函数
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 视图生命周期
    override func loadView() {
        
        // 设置根视图
        var rect = UIScreen.mainScreen().bounds
        rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width + 20, rect.size.height)
        view = UIView.init(frame: rect)
        // 写法2 疑问，直接操作结构属性赋值在swif允许么?
//        var rect = UIScreen.mainScreen().bounds
//        rect.size.width += 20
//        view = UIView.init(frame: rect)
        
        // 以下代码没有设置大小，会导致collectionView.frame = view.bounds也没有大小，从而造成只调用数据源的返回cell个数numberOfItemsInSection的方法但是不会掉用返回cell的cellForItemAtIndexPath方法
        // view = UIView()
//        view.backgroundColor = UIColor.whiteColor()
        
        // 设置界面
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 让collectionView 滚动到指定位置
        collectionView.scrollToItemAtIndexPath(self.currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)
        // Do any additional setup after loading the view.
    }
    
    // MARK: - 懒加载控件
    // 图片浏览视图
    lazy var collectionView : UICollectionView = UICollectionView.init(frame: CGRectZero, collectionViewLayout: PhotoBrowserViewLayout())
    // 保存按钮
    private lazy var saveButton : UIButton = UIButton.init(title: "保存", fontSize: 14, color: UIColor.whiteColor(), imageName: nil,backColor: UIColor.darkGrayColor())
    // 关闭按钮
    private lazy var closeButton : UIButton = UIButton.init(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), imageName: nil,backColor: UIColor.darkGrayColor())
    
    // MARK: - 自定义流水布局
    private class PhotoBrowserViewLayout : UICollectionViewFlowLayout {
        
        // 自定义布局
        private override func prepareLayout() {
            
            super.prepareLayout()
            
            itemSize = (collectionView?.bounds.size)!   // 大小
            minimumInteritemSpacing = 0     // item间距
            minimumLineSpacing = 0      // 行间距
            scrollDirection = UICollectionViewScrollDirection.Horizontal    // 滚动方向
            
            collectionView?.bounces = false     // 取消弹簧效果
            collectionView?.pagingEnabled = true        // 开启分页
            collectionView?.showsHorizontalScrollIndicator = false      // 水平滚动
        }
    }
}

// MARK: - 设置界面
extension PhotoBrowserViewController {

    /// 设置UI
    private func setupUI() {
    
        // 1. 添加控件
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        // 2. 布局
        // 1) 图片浏览视图
        collectionView.frame = view.bounds
        
        // 2) 保存按钮
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSizeMake(100, 36))
        }
        
        // 3) 关闭按钮
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(-8)
            make.size.equalTo(CGSizeMake(100, 36))
        }
        
        // 3. 添加监听方法
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        
        // 4. 准备浏览视图
        prepareForCollectionView()
    }
    
    /// 准备浏览视图 - collectionView
    private func prepareForCollectionView() {
        
        // 1. 注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserCellId)
        
        // 2. 设置数据源
        collectionView.dataSource = self
    }
}

// MARK: - UICollectionViewDataSource
extension PhotoBrowserViewController : UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.imageURL = urls[indexPath.item]
        
        // 设置代理
        cell.Photodelegate = self
        
        return cell
    }
}

// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController : PhotoBrowserCellDelegate {
    
    func photoBrowserCellDidTapImage() {
        close()
    }
    
    func photoBrowserCellDidZoom(scale: CGFloat) {
        
        let isHidden = (scale < 1)
        hideControls(isHidden)
        
        if isHidden {
            // 1. 根据 scale 修改根视图的透明度 & 缩放比例
            view.alpha = scale
            view.transform = CGAffineTransformMakeScale(scale, scale)
        } else {
            view.alpha = 1.0
            view.transform = CGAffineTransformIdentity
        }
    }
    
    /// 隐藏或者显示控件
    private func hideControls(isHidden: Bool) {
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
        
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    }

}

// MARK: - dismiss转场动画协议
extension PhotoBrowserViewController : PhotoBrowserDissmissDelegate {
    
    func imageViewForDissmiss() -> UIImageView {
       
        let imageView = UIImageView()
//        imageView.contentMode = .ScaleAspectFill
//        imageView.clipsToBounds = true
        
        // 1. 设置照片 - 直接从当前显示的 cell 中获取
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        imageView.image = cell.imageView.image
        
        // 2. 转换坐标
        let toRect = cell.convertRect(cell.bounds, toView: UIApplication.sharedApplication().keyWindow)
        imageView.frame = toRect
        
        return imageView
    }
    
    func indexPathForDissmiss() -> NSIndexPath {
        
        return collectionView.indexPathsForVisibleItems()[0]
    }
}